package org.caijin.springzookeeper.Config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.caijin.springzookeeper.Client.ZkClientDemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;



public class ConfigCenter {
    public final static String cluster_connection = "192.168.88.100:2181,192.168.88.101:2181,192.168.88.102:2181";
    private static final Logger log = LoggerFactory.getLogger(ConfigCenter.class);

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = ZkClientDemo.create(cluster_connection);

        config config = new config();
        config.setUsername("anyone");
        config.setPassword("anyValue");

        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = objectMapper.writeValueAsBytes(config);
        Stat stat = zooKeeper.exists("/config", false);
        if (stat == null) {
            // 创建持久节点/config
            zooKeeper.create("/config",bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        Watcher watcher = new Watcher() {
            @SneakyThrows
            @Override
            public void process(WatchedEvent event) {
                if(event.getType()==Event.EventType.NodeDataChanged
                && event.getPath()!=null && event.getPath().equals("/config")){
                    log.info("Path[]发生了数据变化:"+event.getPath());
                    byte[] data = zooKeeper.getData("/config",this,null);
                    config newconfig = objectMapper.readValue(new String(data), config.class);
                    log.info("数据发生了变化:"+newconfig.toString());

                }
            }
        };

        byte[] data = zooKeeper.getData("/config",watcher,null);
        config Oroginalconfig = objectMapper.readValue(new String(data), config.class);
        log.info("初始数据: {}"+ Oroginalconfig);

        Thread.sleep(Integer.MAX_VALUE);

    }

}
